<template>
  <div class="fm-style">
    <a-form
      ref="generateForm"
      :model="models"
      :rules="rules"
      :labelAlign="data.config.labelPosition"
      :labelCol="{ style: `width: ${data.config.labelWidth}px;float:left;   ` }"
      :wrapperCol="{ style: `width: ${data.config.size}%;float:left; ` }"
      layout="horizontal"
      :key="formkey"
    >
      <template v-for="item in data.list">
        <template v-if="item.type === 'grid'">
          <a-row
            :key="item.key"
            type="flex"
            :gutter="item.options.gutter ? item.options.gutter : 0"
            :align="item.options.align"
          >
            <a-col
              v-for="(col, colIndex) in item.columns"
              :key="colIndex"
              :span="col.span"
              :offset="col.offset"
            >
              <template v-for="citem in col.list">
                <genetate-form-item
                  v-if="citem.type !== 'grid'"
                  :key="citem.key"
                  :widget="citem"
                  v-model:models="models"
                  :formdata="flowData.formData"
                ></genetate-form-item>
              </template>
            </a-col>
          </a-row>
        </template>

        <template v-else>
          <genetate-form-item
            :key="item.key"
            :widget="item"
            v-model:models="models"
            :formdata="flowData.formData"
          ></genetate-form-item>
        </template>
      </template>
    </a-form>
  </div>
</template>

<script>
  import GenetateFormItem from './GenerateFormItem'
  // import {loadJs} from '../util/index.js'
  import { GetDictByPid } from '@/api/dictionary/api'
  import { ref } from 'vue'

  export default {
    name: 'FmGenerateForm',
    components: {
      GenetateFormItem,
    },
    // eslint-disable-next-line vue/require-prop-types
    props: ['data', 'value', 'insite', 'flowData'],
    data() {
      return {
        models: {
          subtable: {},
        },
        rules: {},
        formkey: '',
      }
    },

    setup() {
      const generateForm = ref()
      return {
        generateForm,
      }
    },

    created() {
      this.generateModle(this.data.list)
    },
    mounted() {
      var that = this
      if (
        that.flowData !== undefined &&
        that.flowData.formData !== null &&
        that.flowData.formData !== undefined
      ) {
        var formdata = JSON.parse(that.flowData.formData)
        var item = formdata.data
        item.subtable = {}
        formdata.subtable.forEach((element) => {
          item.subtable[element.linktable] = element
        })
        that.models = JSON.parse(JSON.stringify(item))
        that.formkey = new Date().getTime()
        console.log('设置表单数据', JSON.parse(that.flowData.formData))
      } else if (
        that.flowData !== undefined &&
        that.flowData.formDefaultValues !== undefined &&
        that.flowData.formDefaultValues !== null
      ) {
        that.models = JSON.parse(that.flowData.formDefaultValues)
        that.models.subtable = {}
        that.formkey = new Date().getTime()
        console.log(
          '设置表单默认数据',
          JSON.parse(that.flowData.formDefaultValues)
        )
      }
    },
    methods: {
      validatorPhone(rule, value) {
        const phoneNumber = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        // value = this.models[rule.field]
        if (!value) {
          return Promise.reject('手机号码不可为空')
        } else {
          if (!phoneNumber.test(value)) {
            return Promise.reject('手机格式错误')
          } else {
            return Promise.resolve()
          }
        }
      },
      generateModle(genList) {
        for (let i = 0; i < genList.length; i++) {
          if (genList[i].type === 'grid') {
            genList[i].columns.forEach((item) => {
              this.generateModle(item.list)
            })
          } else {
            // 把组件的默认值赋值给表单
            this.models[genList[i].table + '-' + genList[i].field] =
              genList[i].options.defaultValue
            //  把流程对组件状态的控制值赋值给表单
            if (this.flowData.fieldState === undefined) {
              genList[i].fieldState = 0
            } else {
              var item = this.flowData.fieldState.find(
                (s) =>
                  s.tableName === genList[i].table &&
                  s.fieldName == genList[i].field
              )
              genList[i].fieldState = item.state
            }

            // 给表单组件的组件赋值状态
            if (genList[i].type === 'table') {
              genList[i].options.tableSetting.forEach((element) => {
                if (this.flowData.fieldState === undefined) {
                  element.setting.fieldState = 0
                } else {
                  var filedstate = this.flowData.fieldState.find(
                    (s) =>
                      s.tableName === element.setting.table &&
                      s.fieldName == element.setting.field
                  )
                  if (filedstate !== undefined) {
                    element.setting.fieldState = filedstate.state
                  } else {
                    element.setting.fieldState = 0
                  }
                }
              })
            }

            if (genList[i].options.remote == true) {
              GetDictByPid({ id: genList[i].options.remoteFunc }).then(
                (res) => {
                  genList[i].options.remoteOptions = res.content.map((item) => {
                    return {
                      value: item.id,
                      label: item.name,
                    }
                  })
                }
              )
            }
            // 加载表单验证规则
            // if (genList[i].type === 'checkbox') {
            //   this.rules[genList[i].table + '-' + genList[i].field] = [
            //     {
            //       type: 'array',
            //       required: genList[i].options.required,
            //       message: '请选择值',
            //     },
            //   ]
            // }
            switch (genList[i].options.checkType) {
              case 1:
                this.rules[genList[i].table + '-' + genList[i].field] = [
                  {
                    validator: this.validatorPhone,
                  },
                ]
                break
              default:
                if (genList[i].options.required) {
                  this.rules[genList[i].table + '-' + genList[i].field] = [
                    {
                      required: true,
                      message: '值不允许为空',
                    },
                  ]
                }
                break
            }
            // ------
          }
        }
        this.formkey = new Date().getTime()
      },

      getData() {
        var that = this
        // console.log('generateForm', that.generateForm)
        return new Promise((resolve) => {
          that.generateForm
            .validate()
            .then(() => {
              resolve({ tableData: that.data, userData: that.models })
            })
            .catch((error) => {
              console.log('error', error)
            })
        })
      },
      reset() {
        this.$refs.generateForm.resetFields()
      },
    },
  }
</script>
